<?php
/**
 * Created by PhpStorm.
 * User: 12133
 * Date: 2025/7/31
 * Time: 14:25
 */

namespace app\controller\api;


use app\controller\Base;
use app\model\Attr;
use app\service\Email;

class Order extends Base
{
    public function list(){

    }

    public function create(){
        $post = input('post.');
        $amount = 0;
        $string = '';
        global $user;
        $order_no = date('YmdHis').rand(100,999);
        foreach ($post['data'] AS $key => $value){
            $attr = Attr::find($value['id']);
            if (empty($attr->id))continue;
            $amount = bcadd($attr->price,$amount,2);
            $record[] = [
                'order_no' => $order_no,
                'attr_id' => $attr->id,
                'number' => $value['number'],
                'price' => $attr->price,
                'user_id' => $user->id,
                'create_time' => date('Y-m-d H:i:s')
            ];
            $string .= '<tr><td>'.$attr->goods->name.'('.$attr->name.')</td><td>'.$attr->price.'</td></tr>';
        }
        if (!empty($record)){
            $order = \app\model\Order::create([
                'order_no' => $order_no,
                'amount' => $amount,
                'user_id' => $user->id,
                'status' => 1,
                'post_data' => json_encode($post)
            ]);
            $order->record()->saveAll($record);
            $email = new Email();
            $body = file_get_contents(public_path() . '/../view/index/email.html');
            $head = '<caption>用户电子邮箱:'.$post['email'].'</caption><tr><th>商品</th><th>价格</th><th></th></tr>';
            $body = str_replace('{head}', $head, $body);
            $body = str_replace('{content}', $string, $body);
            $email->send($post['email'],'用户'.$user->username.'购买商品列表',$body);
        }
        return $this->msg($order ?? []);
    }
}